<template>
	<view class="w-100">
		<view class="head-style flex-1 fixed-top border-bottom pb-3">
			<view class="flex-1" :style="'height:' + statusBarHeight + 'px;'"></view>
			<view class="flex-1 row-ac mx-3">
				<view class="iconfont icon-search-01"></view>
				<view class="flex-1 row font-s-45 font-w">购物车</view>
			</view>
		</view>
		<view class="flex-1" :style="'height:' + headHeight + 'px;'"></view>
		<view class="flex-1 py-3 bg-white">
			<view class="flex-1 mx-3">
				<view class="flex-1 row" :style="'height:' + dynamicHeight + 'px;'" v-if="cartList.length === 0">
					<view class="flex-1 row-a-j-fc">
						<view class="row-ac">
							<view class="iconfont icon-shopping-01 row"></view>
							<view class="font-s-3 font-w-500 ml-3">购物车空空如也，快去挑选商品吧</view>
						</view>
						<view class="row-ac mt-6">
							<navigator class="rou-box font-s-3" url="/pages/tabar/index" open-type="switchTab">随便逛逛
							</navigator>
							<view class="rou-box font-s-3 ml-4" @click="navTo('/pages/user/my-collection')">查看收藏</view>
						</view>
					</view>
				</view>
				<view class="lex-1 mx-3" v-else>
					<view class="flex-1 cart-item py-4" v-for="(item,index) in cartList" :key="index">
						<view class="flex-1 d-f">
							<view class="pro-img">
								<image :src="item.product.image_list[0].url" mode=""></image>
							</view>
							<view class="flex-1 ml-3">
								<view class="flex-1 d-f">
									<view class="font-s-4 in1line flex-1 font-w">{{ item.product.product_name }}</view>

									<view class="font-s-5 font-w">￥{{ item.product.price }}</view>
								</view>
								<view class="font-s-2 text-light-grey mt-1">
									<text>{{ item.spec || '默认' }}</text>
								</view>
								<view class="flex-1 d-f mt-3">
									<view class="flex-1">
										<view class="change-box">
											<view class="iconfont icon-reduce-01"
												:class="item.quantity > 1 ? 'iconfont-orange' : 'iconfont-grey'"
												@tap="decreaseQuantity(item, index)"></view>
											<!-- <view class="mx-3 mt font-s-4 ">{{ item.quantity }}</view> -->
											<view class="mx-3 mt font-s-4 ">
												<input type="text" v-model="item.quantity" style="width: 80rpx;" />
											</view>
											<view class="iconfont icon-add-01"
												:class="inventoryStata ? 'iconfont-orange' : 'iconfont-grey'"
												@tap="increaseQuantity(item, index)"></view>
										</view>
									</view>
									<view class="font-s-2 mt-2" @tap="deleteItem(item, index)">删除</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="total-amount-box flex-1" v-if="cartTotal > 0">
			<view class="flex-1 row-ac mx-3 mt-2">
				<view class="flex-1 row-ac">
					<view class="font-s-4 font-w">总金额:</view>
					<view class="font-s-7 font-w text-dark ml-1"><text class="font-s-2">￥</text> {{ calculateTotal() }}
					</view>
				</view>
				<view class="checkout-button font-s-4 mr-1" @tap="gotoCheckout">去报单</view>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		addCartItemListsUrl,
		cartItemsUpdateUrl,
		addCartItemsUrl,
		addressListUrl,
		ordersCreateUrl,
		ordersCartCreateUrl
	} from '@/api/index.js'
	export default {
		data() {
			return {
				statusBarHeight: '',
				dynamicHeight: '',
				headHeight: '',
				loginStatus: false,
				cartList: [], // 购物车商品列表
				queryInfo: {
					is_default: 'True'
				},
				queryInfoPro: {
					is_recommend: 'True',
					page: 1,
					page_size: 10
				},
				address: '',
				addressInfo: false,
				inventoryStata: true,
				cartTotal: '',
				token: '',
				updatedData: {
					quantity: ''
				}
			}
		},
		created() {
			this.$getScreenInfo().then(res => {
				this.statusBarHeight = res.statusBarHeight
				this.allWindowHeight = res.windowHeight
				this.calculateDynamicHeight();
			})
			this.token = uni.getStorageSync('token')
			if (this.token != '') {
				this.loginStatus = true
			}
		},
		onLoad() {
			this.init()
		},
		mounted() {
			this.init()
			uni.createSelectorQuery()
				.in(this)
				.select('.head-style')
				.boundingClientRect(data => {
					this.headHeight = data.height;
					this.calculateDynamicHeight();
				})
				.exec();
			this.orderData = {
				cart_items: this.cartList.map(item => ({
					id: item.id,
					product_id: item.product.id,
					quantity: item.quantity,
				})),
			};
		},
		onShow() {
			this.init()
		},
		methods: {
			init() {
				this.getCartList()
				this.getAddressList()
			},
			calculateDynamicHeight() {
				if (this.headHeight && this.allWindowHeight) {
					this.dynamicHeight = this.allWindowHeight - this.headHeight;
				}
			},
			getCartList() {
				if (this.token !== '') {
					this.$R.get(addCartItemListsUrl).then(res => {
						this.cartList = res.data.list
						this.cartTotal = res.data.total
						console.log(this.cartList);
					})
				} else {
					return
				}
			},
			getAddressList() {
				if (this.token !== '') {
					this.$R.get(addressListUrl, this.queryInfo).then(res => {
						if (res.data.list.length == 0) {
							this.addressInfo = false
						} else {
							this.addressInfo = true
							this.address = res.data.list[0]
						}
					})
				} else {
					return
				}
			},
			onPullDownRefresh() {
				console.log('refresh');
				setTimeout(function() {
					uni.stopPullDownRefresh();
				}, 1000);
			},
			decreaseQuantity(item, index) {
				if (this.cartList[index].quantity > 1) {
					this.cartList[index].quantity--;
					this.inventoryStata = true
					this.updatedData.quantity = this.cartList[index].quantity
					this.$R.patch(cartItemsUpdateUrl + item.id + '/', this.updatedData).then(res => {
						console.log(res.msg);
					})
				}
			},
			increaseQuantity(item, index) {
				if (this.cartList[index].quantity >= item.product.inventory) {
					uni.showToast({
						title: '库存数量不足',
						icon: 'none'
					});
					this.inventoryStata = false
				} else {
					this.inventoryStata = true
					this.cartList[index].quantity++;
					this.updatedData.quantity = this.cartList[index].quantity
					this.$R.patch(cartItemsUpdateUrl + item.id + '/', this.updatedData).then(res => {
						console.log(res.msg);
					})
				}
			},
			deleteItem(item, index) {
				console.log(item.id);
				uni.showModal({
					title: '提示',
					content: '是否从购物车中删除',
					success: (res) => {
						if (res.confirm) {
							this.$R.delete(addCartItemsUrl + item.id + '/').then(res1 => {
								console.log(res1);
								if (res1.code == 200) {
									this.getCartList()
								}
							})
							this.cartList.splice(index, 1);
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			calculateTotal() {
				let total = 0
				for (let i = 0; i < this.cartList.length; i++) {
					const item = this.cartList[i]
					total += item.product.price * item.quantity
				}
				return total.toFixed(2) // 保留两位小数
			},
			gotoCheckout() {
				console.log('222', this.orderData);
				this.$R.post(ordersCartCreateUrl, this.orderData)
					.then(res => {
						if (res.code == 200) {
							console.log(res.data);
							this.orderId = res.data.id
							uni.navigateTo({
								url: '/pages/order/report?orderId=' + this.orderId,
							});
						}
					})
					.catch(err => {
						console.error(err);
					});
			},
			navTo(url) {
				uni.navigateTo({
					url: url,
				});
			}
		}
	}
</script>
<style lang="scss">
	.icon-shopping-01 {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #EDEDED;
		color: #C9C9C9;
		font-size: 48rpx;
	}

	.rou-box {
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 28rpx;
		border: 1rpx solid #666;
		color: #666;
		border-radius: 35rpx;
	}

	.cart-item {
		margin-bottom: 25rpx;

		.pro-img {
			width: 160rpx;
			height: 160rpx;

			image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 16rpx;
			}
		}

		.change-box {
			padding: 8rpx 12rpx;
			border: 2rpx solid #B7B7B7;
			display: -webkit-inline-box;

			.iconfont {
				font-size: 46rpx;
			}

			.iconfont-orange {
				color: #000
			}

			.iconfont-grey {
				color: #B8B8B8;
			}

		}
	}

	.total-amount-box {
		height: 120rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;

		.checkout-button {
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 48rpx;
			background-color: #000;
			color: #fff;
		}
	}
</style>